import Sequelize from 'sequelize';
import express from 'express';
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { Order, Delivery } from '../../modal/index'; // 数据库实体类
import { checkPermission, createOrderNumber } from '../../utils/utils'; // 工具类

const router = express.Router();
const permission = ["all"];

router.post('/', async function (Request, Response, next) {
  // 权限校验
  await checkPermission(Request, Response, permission)
  let param = Request.body;
  let addFlag = true; // 为true则新增，false则更新
  await upsertDelivery(param, Response).then(res => {
    addFlag = res;
    if (!res) {
      Response.json({
        message: "success"
      });
    }
  });
  Order.Modal.update({
    status: 3 // 3已发货
  }, {
      where: {
        id: param.orderId,
      }
    }).then(res => {
      if (res && res.length > 0) {
        Response.json({
          data: {},
          message: "success"
        });
      } else {
        Response.status(300).send({ message: "订单查询失败" });
      }
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
});

function upsertDelivery(param, Response) {
  // 更新或创建订单记录
  return new Promise((resolve, reject) => {
    Delivery.Modal.upsert(param).then(res => {
      // res为true则新增，false则更新
      resolve(res)
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

module.exports = router;